package itsm.isperp.module.controller.sparepart;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.sparepart.SptSparepartRelation;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.sparepart.SptSparepartPlanService;
import itsm.isperp.module.service.sparepart.SptSparepartRelationService;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibm.icu.text.SimpleDateFormat;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2016-04-21 18:38
 */
@Controller
@RequestMapping("sparepart/sparepartRelation")
public class SptSparepartRelationController extends
    BaseController<SptSparepartRelation> {

  @Autowired
  protected SptSparepartRelationService sptSparepartRelationService;

  @Autowired
  protected SptSparepartPlanService sptSparepartPlanService;

  @Override
  public SptSparepartRelationService getService() {
    return this.sptSparepartRelationService;
  }

  @Override
  public String getPageTitle() {
    return "出库入关联";
  }

  @RequestMapping("saveRelation")
  @ResponseBody
  public ResultMessage saveRelation(String sparepartId, String ciId,
      String typeKey, HttpServletRequest req) {

    if (ciId != null) {
      String[] ciIds = ciId.split(",");
      for (int i = 0; i < ciIds.length; i++) {

        String tempStatus = "";
        String tempUseStaffId = "";
        String tempUseStaffName = "";
        String sql = "";
        String curCiId = "";
        IUser user = ContextHolder.getLoginUser();
        JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
        SptSparepartRelation sr = new SptSparepartRelation();
        String sql3 ="";

        // 设置默认责任人,状态
        if (typeKey.equals("sparepartOut")) {
          tempStatus = "出库";
          sql = "SELECT a.*,b.fullname,b.name AS use_id FROM spt_sparepart_out a LEFT JOIN app_user b ON a.use_man_id=b.name where a.id='"
              + sparepartId + "'";
          Map<String, Object> mp = jdbcTemplate.queryForMap(sql);
          tempUseStaffId = mp.get("use_id").toString();
          tempUseStaffName = mp.get("fullname").toString();
          curCiId = ciIds[i];
          sql3 = "update spt_sparepart_plan set id=uuid(),status='已出库',support_staff_name='"
              + tempUseStaffName
              + "',support_staff_id='"
              + tempUseStaffId
              + "' where code='"
              + curCiId
              + "' and relation_id='"
              + sparepartId
              + "'";
        } else if (typeKey.equals("sparepartBack")) {
          tempStatus = "";
          // 责任人默认为备件管理员
          tempUseStaffId = user.getUsername();
          tempUseStaffName = user.getFullname();
          curCiId = ciIds[i];
          sql3 = "update spt_sparepart_plan set id=uuid() where code='"
              + curCiId
              + "' and relation_id='"
              + sparepartId
              + "'";

        } else if (typeKey.equals("sparepartDiscard")) {
          tempStatus = "报废";
          // sql="SELECT a.*,b.fullname,b.id AS use_id FROM spt_sparepart_out a LEFT JOIN app_user b ON a.apply_man_id=b.name where a.id='"+sparepartId+"'";
          tempUseStaffId = user.getId();
          tempUseStaffName = user.getFullname();
          curCiId = ciIds[i];
        } else if (typeKey.equals("sparepartIn")) {
          curCiId = ciIds[i];
        }
        sr.setCiId(curCiId);
        sr.setSparepartId(sparepartId);
        sr.setTypeKey(typeKey);
        sr.setStatus(0);
        this.getService().saveOrUpdate(sr);

        // 插入计划变更备件表
        String sql1 = "delete from spt_sparepart_plan where code='" + curCiId
            + "' and relation_id='" + sparepartId + "'";
        String sql2 = "insert into spt_sparepart_plan" + " select a.*,'"
            + sparepartId + "',0 from spt_sparepart a where a.id='" + curCiId
            + "'";
        
        jdbcTemplate.batchUpdate(sql1, sql2, sql3);

      }
      return ResultMessage.newInstance(true);
    } else {
      return ResultMessage.newInstance(false, "没有选择数据");
    }

  }

  @RequestMapping("deleteByCiId")
  @ResponseBody
  public ResultMessage deleteByCiId(String id, String typeKey,
      JqGridRequest request, HttpServletRequest req) {
    this.getService().deleteByCiId(id, typeKey);
    return ResultMessage.newInstance(true);
  }

  @RequestMapping("deleteByCiIdAndSptId")
  @ResponseBody
  public ResultMessage deleteByCiIdAndSptId(String id, String sparepartId,
      JqGridRequest request, HttpServletRequest req) {
    this.getService().deleteByCiIdAndsptId(id, sparepartId);
    return ResultMessage.newInstance(true);
  }

  @RequestMapping("findCiSparepart")
  @ResponseBody
  public PageResponse<Map<String, Object>> findCiSparepart(String ciId,
      JqGridRequest request, HttpServletRequest req) {
    request.addFilterRule("ci_id", JqGridFilterRuleOp.eq, ciId);
    return this.getService().findCiSparepart(request).toPage();
  }

  @RequestMapping("getSptOutByRelateSptInId")
  @ResponseBody
  public Map<String, Object> getSptOutByRelateSptInId(String sptInId,
      JqGridRequest request, HttpServletRequest req) {
    String sql = "select * from spt_sparepart_out where id in(SELECT from_id FROM bpm_process_relation WHERE to_id='"
        + sptInId
        + "' UNION ALL SELECT to_id FROM bpm_process_relation WHERE from_id IN(SELECT from_id FROM bpm_process_relation WHERE to_id='"
        + sptInId + "' ))";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql);
    if (list1.size() > 0)
      return list1.get(0);
    else
      return null;
  }

  @RequestMapping("listSparepartCi")
  @ResponseBody
  public PageResponse<Map<String, Object>> listSparepartCi(String sparepartId,
      JqGridRequest request, HttpServletRequest req) {
    request
        .setSearchString(" a.code in (select ci_id from spt_sparepart_relation where  sparepart_id='"
            + sparepartId + "') and relation_id='" + sparepartId + "'");
    return sptSparepartPlanService.findAllDetailByRequest(request);
  }

}
